<template>
    <div>
        <a-modal
            v-model:visible="toggleVisibleTrigger"
            :title="t('attributeFrom.triggering')"
            :destroy-on-close="true"
            :centered="true"
            width="50%"
            :bodyStyle="{
                height: '400px',
                overflow: 'auto',
                padding: 0
            }"
            wrap-class-name="trigger-wrapper"
            @cancel="handleCancel"
            @ok="handleOk"
        >
            <div class="trigger-wrapper-l">
                <div class="trigger-wrapper-l-h">
                    <span>
                        {{ t('attributeFrom.conditionList') }}
                    </span>
                    <a-icon v-if="rulesList.length < 1" class="add-btn" type="plus-circle" @click="hanldeAddRule" />
                </div>
                <ul class="trigger-wrapper-l-c">
                    <li
                        v-for="rule in rulesList"
                        :key="rule.id"
                        :class="['field-item', { active: rule.active }]"
                        @click="handleClickItem(rule)"
                    >
                        <span class="field-item-name">
                            {{ `${t('attributeFrom.condition')}${rule.name}` }}
                        </span>
                        <span class="del-btn" @click="handleDelRule(rule)">
                            <a-icon type="delete" />
                        </span>
                    </li>
                </ul>
            </div>
            <div class="trigger-wrapper-r">
                <img v-if="!rulesList.length" :src="require('@/assets/img/empty.png')" alt="" class="no-empty" />
                <!-- <filterComponent
          v-if="rulesList.length && condition.id"
          ref="filterComponent"
          :field-list="componentList"
          :condition="condition"
          :show-formula-btn="true"
          :show-serach-btn="false"
          @updateData="handleSetFilterData"
        /> -->
            </div>
        </a-modal>
    </div>
</template>

<script lang="ts">
    import { defineComponent, onMounted, ref, computed, watch } from 'vue'
    import { useI18n } from 'vue-i18n'
    // import filterComponent from 'filterComponent.vue';
    import { cloneDeep } from 'lodash-es'
    import { createUniqueId } from '@/utils/common'
    import { message } from 'ant-design-vue'

    export default defineComponent({
        name: 'TriggerModal',
        components: {
            // filterComponent,
        },
        props: {
            triggeringConditions: {
                type: Array,
                default: () => []
            },
            // 组件列表
            fieldList: {
                type: Array,
                default: () => []
            },
            triggerModalVisible: {
                type: Boolean,
                default: false
            }
        },
        setup(props) {
            const toggleVisibleTrigger = ref(false)
            // 国际化
            const { t } = useI18n()

            // 触发条件
            const condition: any = ref({})

            // 规则列表
            const rulesList = ref<any[]>([])

            // 子组件-ref元素
            const filterComponent = ref()

            const componentList = computed(() => {
                return props.fieldList
            })

            watch(
                () => props.triggerModalVisible,
                () => {
                    toggleVisibleTrigger.value = props.triggerModalVisible
                }
            )

            onMounted(() => {
                rulesList.value = cloneDeep(props.triggeringConditions)
                // 默认选中第一个
                rulesList.value.forEach((item, index) => {
                    if (!index) {
                        item.active = true
                        condition.value = item
                    } else {
                        item.active = false
                    }
                })
            })

            /**
             * 方法部分
             */
            // 添加或者修改触发条件
            const handleSetFilterData = data => {
                condition.value.rule = data
            }

            // 添加规则
            const hanldeAddRule = () => {
                const ids: Array<number> = []
                rulesList.value.forEach(item => {
                    item.active = false
                    // 存在名字id，因为前端删除会存在重复值
                    ids.push(Number(item.name))
                })

                const ruleInfo = {
                    id: createUniqueId(),
                    rule: {},
                    name: ids.length ? Math.max(...ids) + 1 : 1,
                    active: true
                }

                rulesList.value.push(ruleInfo)
                condition.value = ruleInfo
            }

            // 点击
            const handleClickItem = item => {
                if (item.active) {
                    return
                }

                rulesList.value.forEach(rule => {
                    if (rule.id === item.id) {
                        rule.active = true
                    } else {
                        rule.active = false
                    }
                })

                condition.value = item
            }

            // 删除规则
            const handleDelRule = item => {
                const index = rulesList.value.findIndex(rule => rule.id === item.id)
                // 如果删除和当前选中的是一个，那么当前选中清空
                if (rulesList.value[index].id === condition.value.id) {
                    condition.value = {}
                }

                rulesList.value.splice(index, 1)
            }

            // 保存
            const handleSaveData = async () => {
                try {
                    // 逐一去检查是否合格
                    for (let i = 0, len = rulesList.value.length; i < len; i++) {
                        await filterComponent.value?.handleValidate(rulesList.value[i])
                    }
                    return cloneDeep(rulesList.value)
                } catch (error) {
                    message.warning(t('application.formError'))
                    return false
                }
            }

            return {
                t,
                filterComponent,
                componentList,
                toggleVisibleTrigger,
                /**
                 * 方法
                 */
                // 添加或者修改触发条件
                handleSetFilterData,
                // 添加规则
                hanldeAddRule,
                // 点击
                handleClickItem,
                // 删除规则
                handleDelRule,
                // 保存
                handleSaveData
            }
        }
    })
</script>

<style lang="less" scoped>
    .trigger-wrapper {
        position: relative;
        width: 100%;
        height: 100%;
        display: flex;

        .trigger-wrapper-l {
            width: 200px;
            height: 100%;
            padding: 15px 10px;
            border-right: 1px solid #dcdce3;
            display: flex;
            flex-direction: column;

            .trigger-wrapper-l-h {
                height: 37px;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .add-btn {
                    cursor: pointer;
                    color: #468cff;
                }
            }

            .trigger-wrapper-l-c {
                flex: 1;
                min-height: 0;
                list-style: none;
                margin: 0;
                padding: 0;
                overflow: auto;

                .field-item {
                    height: 36px;
                    line-height: 36px;
                    display: flex;
                    align-items: center;
                    border: 1px solid transparent;
                    padding: 4px;
                    transition: all 0.2s;
                    cursor: pointer;
                    margin-bottom: 10px;

                    .field-item-name {
                        flex: 1;
                        min-width: 0;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                    }

                    .del-btn {
                        margin-left: 16px;
                        display: none;
                    }

                    &.active {
                        border: 1px solid #468cff;
                    }

                    &:hover {
                        border: 1px solid #468cff;

                        .del-btn {
                            color: #468cff;
                            display: block;
                        }
                    }
                }
            }
        }

        .trigger-wrapper-r {
            flex: 1;
            height: 100%;
            min-width: 0;
            overflow: auto;
            padding: 15px 10px;
            position: relative;

            .no-empty {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    :deep(.@{ant-prefix}-modal-body) {
        display: flex;
    }
</style>

<i18n>
zh-CN:
  attributeFrom:
    triggering: '触发条件'
    conditionList: '条件列表'
    condition: '条件'
en-US:
  attributeFrom:
    triggering: 'Trigger condition'
    conditionList: 'Condition list'
    condition: 'condition'
</i18n>
